package cn.chenc.framework.jpa.util;

import cn.chenc.framework.jpa.model.PageInfo;
import cn.hutool.core.convert.Convert;
import org.springframework.util.CollectionUtils;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 　@description: TODO
 * 　@author secret
 * 　@date 2021/6/5 23:21
 *
 */
public class SqlHelper {

    public SqlHelper() {
    }

    public static boolean retBool(Integer result) {
        return null != result && result >= 1;
    }

    public static boolean delBool(Integer result) {
        return null != result && result >= 0;
    }

    public static String getCountSQL(String sql) {
        String countSQL = "SELECT COUNT(*) AS totalRow " + sql.substring(sql.toUpperCase().indexOf("FROM"));
        return replaceOrderBy(countSQL);
    }

    public static String replaceOrderBy(String sql) {
        return SqlHelper.Holder.ORDER_BY_PATTERN.matcher(sql).replaceAll("");
    }

    public List<Object> convert(Class<?> clazz, List<Map<String, Object>> list) {
        if (CollectionUtils.isEmpty(list)) {
            return null;
        } else {
            ArrayList result = new ArrayList();

            try {
                PropertyDescriptor[] props = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
                Iterator var5 = list.iterator();

                while(var5.hasNext()) {
                    Map<String, Object> map = (Map)var5.next();
                    Object obj = clazz.newInstance();
                    Iterator var8 = map.keySet().iterator();

                    while(var8.hasNext()) {
                        String key = (String)var8.next();
                        String attrName = key.toLowerCase();
                        PropertyDescriptor[] var11 = props;
                        int var12 = props.length;

                        for(int var13 = 0; var13 < var12; ++var13) {
                            PropertyDescriptor prop = var11[var13];
                            attrName = this.removeUnderLine(attrName);
                            if (attrName.equals(prop.getName())) {
                                Method method = prop.getWriteMethod();
                                Object value = map.get(key);
                                if (value != null) {
                                    value = Convert.convert(prop.getPropertyType(), value);
                                }

                                method.invoke(obj, value);
                            }
                        }
                    }

                    result.add(obj);
                }

                return result;
            } catch (Exception var17) {
                throw new RuntimeException("数据转换错误");
            }
        }
    }

    private String removeUnderLine(String attrName) {
        if (attrName.contains("_")) {
            String[] names = attrName.split("_");
            String firstPart = names[0];
            String otherPart = "";

            for(int i = 1; i < names.length; ++i) {
                String word = names[i].replaceFirst(names[i].substring(0, 1), names[i].substring(0, 1).toUpperCase());
                otherPart = otherPart + word;
            }

            attrName = firstPart + otherPart;
        }

        return attrName;
    }

    public static String getCountSql(String sql) {
        int i = sql.indexOf("from");
        int j = sql.indexOf("FROM");
        int b = 0;
        if (i != -1 && j != -1) {
            if (i < j) {
                b = i;
            } else {
                b = i;
            }
        } else if (j == -1) {
            b = i;
        } else if (i == -1) {
            b = j;
        }

        sql = "select count(*) count " + sql.substring(b);
        return sql;
    }

    public static String queryCountSQL(String sql) {
        String countSQL = "SELECT COUNT(*) AS totalRow   from (" + sql + ") totaltable";
        return countSQL;
    }

    public static String buildDataSql(String sql, PageInfo pageUtil, String datasourceType) {
        StringBuffer dataSql = new StringBuffer();
        if (datasourceType.toLowerCase().contains("oracle")) {
            dataSql.append("SELECT");
            dataSql.append("\t*");
            dataSql.append("FROM");
            dataSql.append("\t(");
            dataSql.append("\t\tSELECT");
            dataSql.append("\t\t\tmintemp.*,");
            dataSql.append("\t\t\tROWNUM num");
            dataSql.append("\t\tFROM");
            dataSql.append("\t\t\t(").append(sql).append(") mintemp");
            dataSql.append("\t\tWHERE");
            dataSql.append("\t\t\tROWNUM <= ").append(pageUtil.getPageSize() * pageUtil.getPageNum());
            dataSql.append("\t) maxtempt WHERE num >").append(pageUtil.getPageSize() * (pageUtil.getPageNum() - 1));
        } else {
            dataSql.append("");
            dataSql.append(sql);
            dataSql.append("  limit " + pageUtil.getPageSize() * (pageUtil.getPageNum() - 1) + "," + pageUtil.getPageSize());
        }

        return dataSql.toString();
    }

    protected static class Holder {
        private static final Pattern ORDER_BY_PATTERN = Pattern.compile("order\\s+by\\s+[^,\\s]+(\\s+asc|\\s+desc)?(\\s*,\\s*[^,\\s]+(\\s+asc|\\s+desc)?)*", 10);

        protected Holder() {
        }
    }

}
